import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { addCartAPI, deleteCartAPI, findNewCartListAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const hasToken = computed(() => userStore.userInfo.token)

  const cartList = ref([])

  // 获取最新购物车列表
  const refreshCart = async () => {
    const { result } = await findNewCartListAPI()
    cartList.value = result
  }

  // 添加购物车操作
  const addToCart = async (sku) => {
    // 已经登录
    if (hasToken.value) {
      await addCartAPI(sku)
      await refreshCart()
      return
    }

    const item = cartList.value.find(v => sku.skuId === v.skuId)
    if (item) {
      item.count++
    } else {
      cartList.value.push(sku)
    }
  }

  // 删除购物车
  const delCart = async (skuId) => {
    if (hasToken.value) {
      await deleteCartAPI([skuId])
      await refreshCart()
      return
    }
    const id = cartList.value.findIndex(v => v.skuId === skuId)
    cartList.value.splice(id, 1)
  }

  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
    const target = cartList.value.find(v => v.skuId === skuId)
    target.selected = selected
  }

  // 全选
  const selectAll = (selected) => {
    cartList.value.forEach(v => v.selected = selected)
  }

  // 清空购物车
  const clearCart = () => {
    cartList.value = []
  }

  // 总的数量 总价钱
  const totalCount = computed(() => cartList.value.reduce((a, b) => a + b.count, 0))
  const totalPrice = computed(() => cartList.value.reduce((a, b) => a + b.count * b.price, 0))

  // 是否全选
  const allSelected = computed(() => cartList.value.every(v => v.selected))

  // 已选择的商品数量
  const selectedCount = computed(() => cartList.value.filter(v => v.selected).reduce((a, b) => a + b.count, 0))

  // 已选择的商品价格合计
  const selectedPrice = computed(() => {
    return cartList.value.filter(v => v.selected).reduce((a, b) => a + b.count * b.price, 0)
  })

  return {
    cartList,
    totalCount,
    totalPrice,
    allSelected,
    selectedCount,
    selectedPrice,
    addToCart,
    delCart,
    singleCheck,
    selectAll,
    clearCart,
    refreshCart
  }
}, { persist: true })
